﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Expo.Training.Entity;
using System.Text.RegularExpressions;
using Expo.Training.BRule;
using System.IO;
using Expo.Training.BRule.Member;
using Expo.Training.BRule.Audit;
using System.Data;
using Expo.Training.BRule.Access;
using System.Net;
using System.Web.Script.Serialization;
using System.Text;
using System.Configuration;

public partial class User_AddUser99XB : PageBase
{
    private Guid rootDepartmentID=Guid.Empty;

    protected void Page_Load(object sender, EventArgs e)
    {
        this.rootDepartmentID = GetRootDepartmentID();
        if (this.rootDepartmentID.Equals(Guid.Empty))
        {
            AddBeginScript("err","系统尚未设定部门信息，请先设定部门信息后再添加用户！");
            return;
        }
        if (!IsPostBack)
        {
            BindCityList();
        }
    }

    //获取99xb的根部门，所有用户都在根部门下（都属于慈溪市教育局）
    private Guid GetRootDepartmentID()
    {
        /*
        Guid rootID = Guid.Empty;
        Department_Info di = new Department_Info();
        di.CustomerID = this.Customer.CustomerID;
        di.ParentID = Guid.Empty;
        if (di.Exist())
        {
            rootID = di.DepartmentID;
        }
        return rootID;
         * */
        //如果部门管理员新增人员将在本部门
        Guid rootDepartmentID = AccessManager.GetMemberRootDepartmentID(this.Member.MemberID, this.Member.CustomerID);
        return rootDepartmentID;
    }

    private void BindCityList()
    {
        this.ddl_WordAddress_Province.DataSource = BindCityDate(1, 0);
        this.ddl_WordAddress_Province.DataTextField = "AreaName";
        this.ddl_WordAddress_Province.DataValueField = "AreaId";
        this.ddl_WordAddress_Province.DataBind();
        this.ddl_WordAddress_Province.Items.Insert(0, new ListItem("  ---  请选择  ---  ", "0"));

        this.ddl_HomeAddress_Province.DataSource = BindCityDate(1, 0);
        this.ddl_HomeAddress_Province.DataTextField = "AreaName";
        this.ddl_HomeAddress_Province.DataValueField = "AreaId";
        this.ddl_HomeAddress_Province.DataBind();
        this.ddl_HomeAddress_Province.Items.Insert(0, new ListItem("  ---  请选择  ---  ", "0"));
    }

    private DataTable BindCityDate(int nodeType, int areaKey)
    {
        DataTable objData = new DataTable();
        City_Info objCity = new City_Info();
        objCity.NodeType = nodeType;
        objCity.AreaKey = areaKey;
        objCity.OrderBy = "Px";
        objData = objCity.QueryDataTable();
        objCity.Dispose();
        return objData;
    }


    #region 添加用户信息
    protected void but_Add_Click(object sender, EventArgs e)
    {
        int wordAddress_Province = Convert.ToInt32(this.ddl_WordAddress_Province.SelectedValue.ToString());
        int wordAddress_City = Convert.ToInt32(this.hd_WordAddress_City.Value.ToString());
        int wordAddress_Area = Convert.ToInt32(this.hd_WordAddress_Area.Value.ToString());

        int homeAddress_Province = Convert.ToInt32(this.ddl_HomeAddress_Province.SelectedValue.ToString());
        int homeAddress_City = Convert.ToInt32(this.hd_HomeAddress_City.Value.ToString());
        int homeAddress_Area = Convert.ToInt32(this.hd_HomeAddress_Area.Value.ToString());
        string nickname = this.txt_NickName.Text.Trim();
        string useraccount = this.txt_UserAccount.Text.Trim();
        string password = this.txt_Password.Text.Trim();
        string password2 = this.txt_Password2.Text.Trim();
        string cellphone = this.txt_CellPhone.Text.Trim();
        string email = this.txt_Email.Text.Trim();
        string realname = this.txt_RealName.Text.Trim();
        //int lastDays = txt_LastDays.Text.Trim() != string.Empty ? Int32.Parse(this.txt_LastDays.Text.Trim()) : 0;

        #region 服务器验证

        sp_UserAccount.Attributes.Add("style", "display:none");
        sp_UserAccount2.Attributes.Add("style", "display:none");

        sp_Password2.Attributes.Add("style", "display:none");
        sp_Password3.Attributes.Add("style", "display:none");
        //sp_Email.Attributes.Add("style", "display:none");
        sp_Email2.Attributes.Add("style", "display:none");
        sp_Email3.Attributes.Add("style", "display:none");
        sp_Realname.Attributes.Add("style", "display:none");
        sp_Nickname.Attributes.Add("style", "display:none");

        spCardID.Attributes.Add("style","display:none");

        if (useraccount.Length == 0)
        {
            sp_UserAccount.Attributes.Add("style", "display:''");
            AddEndScript("unsuccessful", "alert('用户名不能为空！');");
            return;
        }
        else
        {
            Member_Info objM = new Member_Info();
            objM.UserAccount = useraccount;
            objM.CustomerID = this.Member.CustomerID;
            if (objM.Exist())
            {
                this.sp_UserAccount2.Attributes.Add("style", "display:''");
                return;
            }
        }

        if (password.Length > 0 && password.Length < 8)
        {
            AddEndScript("wrong", "alert('密码必须至少8位字符！');");
            return;
        }
        if (password != password2)
        {
            sp_Password2.Attributes.Add("style", "display:''");
            return;
        }

        if (realname.Length == 0)
        {
            sp_Realname.Attributes.Add("style", "display:''");
            AddEndScript("unsuccessful", "alert('真实姓名不能为空！');");
            return;
        }
        if (nickname.Length == 0)
        {
            sp_Nickname.Attributes.Add("style", "display:''");
            AddEndScript("unsuccessful", "alert('昵称不能为空！');");
            return;
        }

        //if (email.Length == 0)
        //{
        //    sp_Email.Attributes.Add("style", "display:''");
        //    AddEndScript("unsuccessful", "alert('E-Mail不能为空！');");
        //    return;
        //}
        if (email.Length > 0)
        {
            Regex gRegPostCode = new Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            if (!gRegPostCode.IsMatch(email))
            {
                sp_Email2.Attributes.Add("style", "display:''");
                return;
            }
            else
            {
                Member_Info objM = new Member_Info();
                objM.CustomerID = this.Member.CustomerID;
                objM.Email = email;
                if (objM.Exist())
                {
                    sp_Email3.Attributes.Add("style", "display:''");
                    return;
                }
            }
        }

        if (ddl_CardType.SelectedValue.Equals("1"))
        {
            if (this.txt_IDCard.Text.Length != 0)
            {
                if (txt_IDCard.Text.Trim().Length == 18)
                {
                    //Regex reg = new Regex(@"^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{4}$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                    //if (!reg.IsMatch(this.txt_IDCard.Text))
                    //{
                    //    this.AddEndScript("wrong", "alert('身份证号码输入不正确！')");
                    //    return;
                    //}
                    string chkMsg = PublicFunction.CheckCidInfo(this.txt_IDCard.Text).ToUpper();
                    if (!chkMsg.Contains("CHKPASS"))
                    {
                        this.AddEndScript("wrong", "alert('身份证号码输入不正确！" + chkMsg + "')");
                        return;
                    }
                    else
                    {
                        Member_Info objMem = new Member_Info();
                        objMem.IDCard = this.txt_IDCard.Text;
                        objMem.CustomerID = this.Customer.CustomerID;
                        objMem.Stutas = 0;
                        if (objMem.Exist())
                        {
                            objMem.Dispose();
                            this.AddEndScript("wrong1", "alert('身份证号码已存在！')");
                            return;
                        }
                        else
                        {
                            objMem.Dispose();
                            objMem = new Member_Info();

                            objMem.IDCard = VerifyIDCardNumber.GetAnotherID(this.txt_IDCard.Text);
                            objMem.CustomerID = this.Customer.CustomerID;
                            if (objMem.Exist())
                            {
                                objMem.Dispose();
                                this.AddEndScript("wrong1", "alert('对应15或18号身份证号码已存在！')");
                                return;
                            }
                        }
                        objMem.Dispose();
                    }
                }
                else
                {
                    this.AddEndScript("wrong1", "alert('身份证号码必须是18位！')");
                    return;
                }
            }
            else
            {
                this.AddEndScript("wrong1", "alert('身份证号码不能为空！')");
                return;
            }
        }
        if (this.File1.PostedFile.ContentLength > 204800)
        {
            this.AddEndScript("error", "alert('头像图片过大！');");
            return;
        }

        //2013.3.8验证学习卡
        string cardID = txtCardID.Text;
        if (cardID.Trim().Length != 0)
        {
            MemberCard_Info mci = new MemberCard_Info();
            mci.CardID = cardID;
            if (mci.Exist())
            {
                this.AddEndScript("wrong1", "alert('学习卡号码已存在！')");
                mci.Dispose();
                return;
            }
        }
        #endregion

        //Customer_Access objCA = new Customer_Access();
        //objCA.CustomerID = this.Member.CustomerID;
        //if (objCA.Exist())
        //{
        //    if (objCA.AccountLicense > 0 && (objCA.AccountLicense - objCA.UseAccountLicence) < 1)
        //    {
        //        this.AddEndScript("error", "alert('当前已开账号数已达到企业最大帐号数限制！');");
        //        return;
        //    }
        //}
        //else
        //{
        //    this.AddEndScript("error", "alert('添加失败！');");
        //    return;
        //}

        if (ddl_CardType.SelectedValue == "1")
        {
            ddl_Sex.SelectedValue = CheckIDCardSex(txt_IDCard.Text.Trim()).ToString();
        }
        Member_Info objMember = new Member_Info();
        objMember.MemberID = Guid.NewGuid();
        objMember.UserAccount = useraccount;
        objMember.NickName = nickname;
        objMember.RealName = realname;
        objMember.Sex = int.Parse(ddl_Sex.SelectedValue);
        objMember.Duty = txt_Duty.Text.Trim();
        objMember.CardType = Int32.Parse(ddl_CardType.SelectedValue);
        objMember.IDCard = txt_IDCard.Text.Trim();
        objMember.Email = email;
        objMember.CellPhone = cellphone;
        //objMember.HomeAddress = txt_HomeAddress.Text.Trim();
        objMember.WorkAddress_Province = wordAddress_Province;
        objMember.WorkAddress_City = wordAddress_City;
        objMember.WorkAddress_Area = wordAddress_Area;
        objMember.HomeAddress_Province = homeAddress_Province;
        objMember.HomeAddress_City = homeAddress_City;
        objMember.HomeAddress_Area = homeAddress_Area;
        if (password.Length > 0)
            objMember.Password = PublicFunction.EnPassword(password);
        else
            objMember.Password = PublicFunction.EnPassword("12345678");
        //objMember.LastDays = CustomerCode == "ZO" ? lastDays : 0;
        objMember.CustomerID = this.Member.CustomerID;
        DateTime periodDate = DateTime.Parse("1900-1-1");
        objMember.PeriodDate = periodDate;

        string folderName = ResolveClientUrl("~/Data/Header/");
        if (!Directory.Exists(Server.MapPath(folderName)))
        {
            Directory.CreateDirectory(Server.MapPath(folderName));
        }
        string fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
        string fileExtension = Path.GetExtension(this.File1.PostedFile.FileName).ToUpper();
        if (fileExtension.Length != 0)
        {
            string filePath = Server.MapPath(folderName + fileName + fileExtension);
            if (!(fileExtension == ".JPEG" || fileExtension == ".JPG" || fileExtension == ".PNG" || fileExtension == ".GIF"))
            {
                this.AddEndScript("error", "alert('不支持的头像图片格式！');");
                return;
            }
            this.File1.PostedFile.SaveAs(filePath);
            CutImage image = new CutImage();
            image.CutImageSquare(filePath, Server.MapPath(folderName + fileName + "_s" + fileExtension), 71);
            //image.CutImageSquare(filePath, Server.MapPath(folderName + fileName +  fileExtension), 71);
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
            objMember.HeaderUrl = fileName + "_s" + fileExtension;
        }
        else
        {
            objMember.HeaderUrl = "";
        }
        objMember.Stutas = MemberConst.MEMBER_STATUS_START;  //正常，无需审核直接通过
        objMember.Creator = this.Member.MemberID;

        //2013.3.8 增加教师，志愿者相关信息
        //objMember.MemberType = int.Parse(ddlMemberType.SelectedValue);
        //objMember.Specialty = txtSpecialty.Text;
        if (chkIsVolunteer.Checked)
        {
            objMember.Volunteer = 1;
        }
        else
        {
            objMember.Volunteer = 0;
        }
        //objMember.Memo = txtMemo.Text;

        if (objMember.Add())
        {
            Guid memberid = objMember.MemberID;
            string realdName = objMember.RealName;

            Member_Detail objDetail = new Member_Detail();
            objDetail.MemberID = objMember.MemberID;
            objDetail.Add();
            // 新增该用户的用户标签
            Expo.Training.BRule.Exam.QuestionManager.AddAttributes(objMember.MemberID, ta_Attributes.SelectedValue);

            //2013.3.8添加学习卡信息
            MemberCard_Info mci = new MemberCard_Info();
            mci.MemberID = objMember.MemberID;
            mci.CardID = cardID;
            if (!mci.Exist())
            {
                mci.MemberID = objMember.MemberID;
                mci.CardID = cardID;
                mci.Add();
            }
            mci.Dispose();

            //如果学员有学习卡则添加vip信息
            /**if (!string.IsNullOrEmpty(cardID))
            {
                Department_Info objDI = new Department_Info();
                objDI.DepartmentID = this.rootDepartmentID;
                if (objDI.Exist())
                {
                    Expo.Training.DataAccess.Vip.VipEntity objVip = new Expo.Training.DataAccess.Vip.VipEntity();
                    objVip.MemberID = objMember.MemberID;
                    if (objDI.DeptType == 1)
                    {
                        //创建者为市县默认学员为vip-lv1
                        objVip.Category = 2;
                    }
                    else
                    {
                        //创建者为其他时默认学员为vip-lv1
                        objVip.Category = 1;
                    }
                    Expo.Training.DataAccess.Vip.VipModule.AddVip(objVip);
                }
            }**/

            Member_Department objMD = new Member_Department();
            objMD.MemberID = objMember.MemberID;
            objMD.DepartmentID = this.rootDepartmentID;
            if (objMD.Add())
            {

                Audit.AuditLog(this.Member.MemberID, string.Format("{0}|{1}|{2},{3},{4}|{5}", "用户信息录入", "添加", objMember.UserAccount, objMember.RealName, "已录入", "成功"));
                AddEndScript("add succes", "alert('添加用户成功！');location.href='ManagementUser.aspx'");
            }


            WebClient wc = new WebClient();
            //增加是否为管理员的参数
            Member_Group mg = new Member_Group();
            Member_Department md = new Member_Department();
            string DepartmenID = "0";
            md.MemberID = objMember.MemberID;
            mg.MemberID = objMember.MemberID;
            if (mg.Exist())
            {
                if (md.Exist())
                {
                    DepartmenID = md.DepartmentID.ToString();
                }
            }
            string userAccount = objMember.UserAccount;
            string userPwd = objMember.Password;
            //string sendData = "userAccount=" + userAccount + "&userPassword=" + userPwd +
            //                    "&sn=2014CiXiXfYh&memberId=" + objMember.MemberID + "&realName=" + objMember.RealName;
            string sendData = "userAccount=" + userAccount + "&userPassword=" + userPwd +
                "&sn=2014CiXiXfYh&memberId=" + objMember.MemberID + "&realName=" + objMember.RealName +
                "&userType=" + DepartmenID + "&departmentid=" + DepartmenID;
            byte[] postData = Encoding.GetEncoding("UTF-8").GetBytes(sendData.ToString());
            wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            wc.Headers.Add("ContentLength", sendData.Length.ToString());
            string Url = ConfigurationManager.AppSettings["Bank"] + "services/UserManager/editUser";
            byte[] recData = wc.UploadData(Url, "Post", postData);
            string JSON = Encoding.GetEncoding("UTF-8").GetString(recData);
            //this.AddEndScript("wrong", "alert('" + al + "');");
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            Dictionary<string, object> json = (Dictionary<string, object>)serializer.DeserializeObject(JSON);
            foreach (KeyValuePair<string, object> str in json)
            {
                if (str.Key.Equals("result"))
                {
                    string val = str.Value.ToString();
                    if (val != "0")
                    {
                        AddEndScript("add succes", "alert('学分用户未同步成功！')");
                    }
                }
            }
        }
    }
    #endregion

    private int CheckIDCardSex(string IDCard)
    {
        int idSex = 0;
        try
        {
            idSex = int.Parse(IDCard.Substring(16, 1));
            if (idSex % 2 == 0)
            {
                idSex = 2;
            }
            else
            {
                idSex = 1;
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return idSex;
    }
}